package io.github.jsp.service.impl;


import io.github.jsp.dao.TaskMapper;
import io.github.jsp.model.Task;
import io.github.jsp.model.TaskExecution;
import io.github.jsp.scheduler.TaskScheduler;
import io.github.jsp.service.TaskService;
import io.github.jsp.util.CronExpressionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class TaskServiceImpl implements TaskService {

    private final TaskMapper taskMapper;
    private final TaskScheduler taskScheduler;

    @Autowired
    public TaskServiceImpl(TaskMapper taskMapper, TaskScheduler taskScheduler) {
        this.taskMapper = taskMapper;
        this.taskScheduler = taskScheduler;
    }

    @Override
    public List<Task> findAllEnabledTasks() {
        return taskMapper.findAllEnabledTasks();
    }

    @Override
    public Task findTaskById(int id) {
        return taskMapper.findTaskById(id);
    }

    @Override
    @Transactional
    public boolean addTask(Task task) {
        int result = taskMapper.insertTask(task);
        if (result > 0 && "ENABLED".equals(task.getStatus())) {
            taskScheduler.scheduleTask(task);
        }
        return result > 0;
    }

    @Override
    @Transactional
    public boolean updateTask(Task task) {
        int result = taskMapper.updateTask(task);
        if (result > 0 && "ENABLED".equals(task.getStatus())) {
            taskScheduler.scheduleTask(task);
        }
        return result > 0;
    }

    @Override
    @Transactional
    public boolean deleteTask(int id) {
        return taskMapper.deleteTask(id) > 0;
    }

    @Override
    @Transactional
    public boolean toggleTaskStatus(int id, String status) {
        Task task = taskMapper.findTaskById(id);
        if (task == null) {
            return false;
        }
        
        task.setStatus(status);
        int result = taskMapper.updateTask(task);
        if (result > 0 && "ENABLED".equals(status)) {
            taskScheduler.scheduleTask(task);
        }
        return result > 0;
    }

    @Override
    public boolean executeTaskNow(int id) {
        Task task = taskMapper.findTaskById(id);
        if (task == null) {
            return false;
        }
        
        taskScheduler.scheduleTask(task);
        return true;
    }

    @Override
    public List<TaskExecution> getTaskExecutionHistory(int taskId) {
        return taskMapper.findTaskExecutionHistory(taskId);
    }

    @Override
    public Date getNextRunTime(String cronExpression) {
        return CronExpressionUtil.getNextRunTime(cronExpression);
    }
}